<?php

namespace statistics\utils;

/**
 * ****************************************************************************
 * Hilsklasse zum Verwalten der Statistiken in der DB
 *
 * Copyright : (c) 2004 - 2012 The Admidio Team
 * Homepage : http://www.admidio.org
 *
 * License : GNU Public License 2 http://www.gnu.org/licenses/gpl-2.0.htm
 *
 * Parameters:
 *
 * ***************************************************************************
 */
require_once (SERVER_PATH . '/adm_program/system/classes/table_access.php');
require_once (substr ( __DIR__, 0, strpos ( __DIR__, 'statistics' ) + 10 ) . DIRECTORY_SEPARATOR . 'includes.php');
require_once (STATISTICS_PATH . '/utils/db_constants.php');

use \TableAccess;
use \Exception;
use statistics\model\statistic\Statistic;
use statistics\model\statistic\StatisticTable;
use statistics\model\statistic\StatisticTableColumn;
use statistics\model\statistic\StatisticTableRow;
use statistics\model\statistic\StatisticCondition;
use statistics\model\statistic\StatisticFunction;

class DBAccess {
	private $tableStatistics;
	private $tableTables;
	private $tableColumns;
	private $tableRows;
	private $DBAccessInitialized = false;
	private static $instance = null;
	
	public static function getInstance() {
		if (self::$instance === null) {
			self::$instance = new self ();
		}
		return self::$instance;
	}
	private function __construct() {
		try {
			$this->initTableAccess ();			
		} catch ( Exception $e ) {
			$this->DBAccessInitialized = false;
		}
	}
	private function checkDBAccessible() {
		global $gDb;
		$result = $gDb->query ( "SHOW TABLES LIKE '" . TBL_STATISTICS . '\'' );
		$table = $gDb->num_rows ( $result );
		if ($table < 1) {
			throw new Exception ( 'DB for Statistics not accessible.' );
		}
	}
	private function initTableAccess() {
		global $gDb;
		$this->checkDBAccessible ();
		$this->tableStatistics = new TableAccess ( $gDb, TBL_STATISTICS, 'sta' );
		$this->tableTables = new TableAccess ( $gDb, TBL_TABLES, 'stt' );
		$this->tableColumns = new TableAccess ( $gDb, TBL_COLUMNS, 'stc' );
		$this->tableRows = new TableAccess ( $gDb, TBL_ROWS, 'str' );
		$this->DBAccessInitialized = true;
	}
	private function checkDBBeforeAccess() {
		if ($this->DBAccessInitialized) {
			$this->checkDBAccessible ();
		} else {
			$this->initTableAccess ();
		}
	}
	public function getTableStatistics() {
		$this->checkDBBeforeAccess();
		return $this->tableStatistics;
	}
	public function getTableTables() {
		$this->checkDBBeforeAccess();
		return $this->tableTables;
	}
	public function getTableColumns() {
		$this->checkDBBeforeAccess();
		return $this->tableColumns;
	}
	public function getTableRows() {
		$this->checkDBBeforeAccess();
		return $this->tableRows;
	}
	public function isPluginInstalled() {
		return $this->DBAccessInitialized;
	}
}

